package com.buddy.learn.javasource._volatile;

/**
 * 一致性，有序性，原子性
 *
 * 1. 证明乱序存在；
 * 2. 为什么存在乱序？
 * 3. 什么样的指令存在乱序？不影响单线程的最终一致性
 *      前后不影响的：x = 1；y=x+1；肯定不会乱序
 * @author Buddy
 * @date 2021/5/7
 */
public class _002验证JAVA执行指令重排序 {
    private static int x = 0, y = 0;
    private static int a = 0, b = 0;

    public static void main(String[] args) throws InterruptedException {
        int i = 0;
        for (; ; ) {
            i++;
            x = 0;
            y = 0;
            a = 0;
            b = 0;
            Thread one = new Thread(() -> {
                a = 1;
                x = b;
            });

            Thread other = new Thread(() -> {
                b = 1;
                y = a;
            });
            one.start();
            other.start();
            one.join();
            other.join();
            String result = "第【" + i + "】次(x=" + x + ",y=" + y + ")";
            if (x == 0 && y == 0) {
                // 当 x = 0，y=0说明两个线程的执行顺序肯定不对了。
                System.out.println(result);
            }
        }
    }
}
